package com.xl.baseMethod;

import lombok.extern.slf4j.Slf4j;

import static java.lang.Thread.sleep;

/**
 * JdkVersion: 1.8
 * Author: lei·xie
 * Created: 2024/8/5 0002 10:22
 * Description: 基本方法 interrupt监控
 */
@Slf4j(topic = "b.Test10")
public class ThreadDemo10 {
    public static void main(String[] args) throws InterruptedException{
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        sleep(5000);
        tpt.stop();
    }

}

@Slf4j(topic = "b.TwoPhaseTermination")
class TwoPhaseTermination{
    private Thread monitor;
    //启动监控线程
    public void start(){
        monitor = new Thread(() -> {
            while (true){
                Thread current = Thread.currentThread();
                if (current.isInterrupted()){
                    log.debug("料理后事");
                    break;
                }
                try {
                    sleep(1000); //情况1，睡眠过程中被打断
                    log.debug("执行监控记录"); //监控记录时被打断
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标记
                    current.interrupt();
                }
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }
}
